﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace WPClient
{
    public partial class MainPage : PhoneApplicationPage
    {
        Socket mySocket = null;
        ManualResetEvent MyEvent = null;
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (mySocket == null)
            {
                mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            if (MyEvent == null)
            {
                MyEvent = new ManualResetEvent(false);
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (mySocket != null)
            {
                mySocket.Shutdown(SocketShutdown.Both);
                mySocket.Close();
            }
            base.OnNavigatedFrom(e);
        }

        private void onConnect(object sender, RoutedEventArgs e)
        {
            if (mySocket != null)
            {
                SocketAsyncEventArgs connArg = new SocketAsyncEventArgs();
                // 要连接的远程服务器
                connArg.RemoteEndPoint = new DnsEndPoint(this.txtServerIP.Text, 1377);
                // 操作完成后的回调
                connArg.Completed += (sendObj, arg) =>
                {
                    if (arg.SocketError == SocketError.Success) //连接成功
                    {
                        Dispatcher.BeginInvoke(() => txtbInfo.Text = "连接成功。");
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            txtbInfo.Text = "连接失败，错误：" + arg.SocketError.ToString();
                        });
                    }
                    // 向调用线程报告操作结束
                    MyEvent.Set();
                };
                // 重置线程等待事件
                MyEvent.Reset();
                txtbInfo.Text = "正在连接，请等候……";
                // 开始异连接
                mySocket.ConnectAsync(connArg);
                // 等待连接完成
                MyEvent.WaitOne(6000);
            }
        }

        private void onPause(object sender, RoutedEventArgs e)
        {
            SendCommand("pause");
        }

        private void onStop(object sender, RoutedEventArgs e)
        {
            SendCommand("stop");
        }

        private void onPlay(object sender, RoutedEventArgs e)
        {
            SendCommand("play");
        }


        private void SendCommand(string txt)
        {
            if (mySocket != null && mySocket.Connected)
            {
                SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs();
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(txt);
                sendArg.SetBuffer(buffer, 0, buffer.Length);
                // 发送完成后的回调 
                sendArg.Completed += (objSender, mArg) =>
                {
                    // 如果操作成功
                    if (mArg.SocketError == SocketError.Success)
                    {
                        Dispatcher.BeginInvoke(() => txtbInfo.Text = "发送成功。");
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            this.txtbInfo.Text = "发送失败，错误：" + mArg.SocketError.ToString();
                        });
                    }
                    // 报告异步操作结束
                    MyEvent.Set();
                };
                // 重置信号
                MyEvent.Reset();
                txtbInfo.Text = "正在发送，请等候……";
                // 异步发送
                mySocket.SendAsync(sendArg);
                // 等待操作完成
                MyEvent.WaitOne(6000);
            }
        }
    }
}